package com.yc.backstage.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.lang.UUID;
import com.yc.backstage.common.service.AuthorizationServieImpl;
import com.yc.backstage.entity.SysMenu;
import com.yc.backstage.entity.SysUser;
import com.yc.backstage.entity.vo.LoginVO;
import com.yc.backstage.entity.vo.RegisterVO;
import com.yc.backstage.service.SysMenuService;
import com.yc.backstage.service.SysPermissionService;
import com.yc.backstage.utils.SecurityUtils;
import com.yc.common.constant.Constants;
import com.yc.common.empty.GenerateCode;
import com.yc.common.expection.BusinessException;
import com.yc.common.expection.UserPasswordNotMatchException;
import com.yc.common.res.ResultClass;
import com.yc.common.enums.ResultCode;
import com.yc.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Classname AuthorizationController
 * @Description 用户自定义认证
 * @Version 1.0.0
 * @Date 2022/8/2 15:12
 * @Created by Mikechen
 */
@RestController
@RequestMapping("/")
public class AuthorizationController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AuthorizationServieImpl authorizationServie;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysMenuService SysMenuService;


    /**
     * 功能描述：获取图片验证码
     *
     * @author: mikechen
     * @date: 2022/7/16 12:59
     */
    @GetMapping("/captchaImage")
    public ResultClass getCaptchaImage() {
        //生成uuid作为key
        String key = UUID.randomUUID().toString();
        //创建图片对象
        GenerateCode generateCode = new GenerateCode();
        //获取验证码图片流
        BufferedImage image = generateCode.getImage();
        //获取验证码文本
        String code = generateCode.getText();
        //放入redis 并设置默认的过期时间
        redisUtils.putAndexpire(key, code);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return ResultClass.fail(ResultCode.SERVER_ERROR.getCode(), "图片流异常");
        }
        HashMap<String, Object> map = new HashMap<>();
        //转换为base64形式的文件流
        map.put("img", Base64.encode(os.toByteArray()));
        map.put("uuid", key);
        return ResultClass.success(map);
    }

    /**
     * 功能描述：登录
     *
     * @author: mikechen
     * @date: 2022/7/20 8:41
     */
    @PostMapping("/login")
    public ResultClass login(@RequestBody LoginVO loginVO) {
        try {
            if(redisUtils.get(loginVO.getUuid())==null||!loginVO.getCode().equals(redisUtils.get(loginVO.getUuid()).toString())){
                return ResultClass.fail("验证码错误");
            }
            String token = authorizationServie.login(loginVO.getUsername(), loginVO.getPassword());
            Map<String, String> map = new HashMap<>();
            map.put(Constants.TOKEN, token);
            return ResultClass.success(map);
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof UserPasswordNotMatchException){
                return ResultClass.fail(201,"用户名密码不匹配");
            }
            if(e instanceof BusinessException){
                return ResultClass.fail(e.getMessage());
            }
            return ResultClass.fail(201,"接口异常,请稍后再试");
        }
    }

    /**
     * 获取用户详细信息
     *
     * @return
     */
    @GetMapping ("/getInfo")
    public ResultClass getInfo() {
        // 用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return ResultClass.success(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public ResultClass getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = SysMenuService.selectMenuTreeByUserId(userId);
        return ResultClass.success(SysMenuService.buildMenus(menus));
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public ResultClass logout(HttpServletRequest request) {
        //清除token的信息
        return ResultClass.success();
    }

    @PostMapping("/register")
    public ResultClass register(@RequestBody RegisterVO registerVO) {
        String msg = authorizationServie.register(registerVO);
        return ResultClass.success(msg);
    }
}
